import fs from "fs";
import path from "path";
import express, { request } from "express";
import bodyParser from "body-parser";
import uuid from "node-uuid";
import { imgBuilderArr2 } from "./fileBuilder";
// import "./socket.server";
import {serverPC} from"./server_PC"; // 引入 pc 接口

import {
    userApprove,
    dbConnTest,
    userRegister,
    userLogin,
    userUpdate,
    userLogins,
    bookSellRelease,
    getBookOnSellNearBy,
    FavoriteBookList,
    getBookinfo,
    getMeOnSellBookList,
    getAlterthepriceBook,
    getAddaddress,
    getAlladdress,
    updateAddaddress,
    delAddress,
    getMefavorites,
    setFavorite,
    sendComment,
    getBookComments,
    getorderLists,
    getOrder,
    getMeMessageAll,
    pullChatRecords,
    searchBookByType,
    getHotLists,
    getAllorders,
    getGoods,
    getorders, 
    searchBooksByKey,
} from "./mySqlHandler";
const gloabl = {
    port: 3205,
    publicPath: path.join(__dirname, "public"),
    dataPath: path.join(__dirname, "data"),
}
const filePath = path.join(__dirname, './public')
const app = express();

const appConfig = () => {
    app.use(bodyParser.json({ limit: '50mb' }));
    app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));
    app.use(express.json({ limit: '50mb' }));
    app.use(express.urlencoded({ limit: '50mb' }));
    app.use(express.static(gloabl.publicPath));
}
appConfig();

// qrDecode(gloabl.dataPath +"/22.jpg",res=>{
//     console.log(res);
// })

app.listen(gloabl.port, () => {
    console.log("---> data-server-running");
    console.log("http://localhost:" + gloabl.port);
});

serverPC(app); // 加载 pc 接口

// 管理员登录
app.post("/loginAdmin", (request, response) => {
    let loginUser = request.body;
    let msgBody = {
        code: "01",
        msg: "验证通过",
        data: null
    };

    if (!fs.existsSync(path.join(gloabl.dataPath, "userInfoAdmin.json"))) {
        msgBody = {
            code: "404",
            msg: "管理员数据连接失败",
            data: null
        };
        return response.send(msgBody);
    }

    let users = JSON.parse(fs.readFileSync(path.join(gloabl.dataPath, "userInfoAdmin.json"), "utf-8"));
    let target = users.find(item => item.username === loginUser.username);

    if (!target) {
        msgBody = {
            code: "02",
            msg: "管理员不存在",
            data: null
        }
    } else {
        if (target.password !== loginUser.password) {
            msgBody = {
                code: "03",
                msg: "密码错误",
                data: null
            }
        } else {
            delete target.pass;
            msgBody.data = target;
        }
    }
    response.send(msgBody);
});

/*----------------以上为管理员接口------------------*/

// 数据库连接测试
app.get("/dbconntest", (request, response) => {
    dbConnTest(res => {
        if (res.code == "01") {
            response.send({ code: "01", msg: "ok", data: res.data });
        } else {
            console.log("dbconntest-->",res);
            response.send({ code: "04", msg: "error", data: res });
        }
    });
})

/*---获取验证码---*/
app.get("/getVerfityCode", (request, response) => {
    let query = request.query;
    console.log("query->>>", query);
    let vercode = "";
    for (let i = 0; i < 4; i++) {
        vercode += Math.floor(Math.random() * 10);
    }
    response.send({ code: "01", msg: "test", data: vercode });
});

// 用户注册
app.post("/register", (request, response) => {
    let { nickname, password, phonenum } = request.body
    userRegister(uuid.v1(), nickname, password, phonenum, res => {
        if (res.code == "01") {
            response.send({ code: "01", msg: "ok", data: res.data });
        } else {
            response.send({ code: "03", msg: "error", data: null });
        }
    })
})

//用户登录
app.get("/login", (request, response) => {
    let { password, phonenum } = request.query
    userLogin(phonenum, password, res => {
        if (res.code === "01") {
            if (res.data.length >= 1) {
                response.send({ code: "01", msg: "ok", data: res.data[0] });
            } else {
                response.send({ code: "02", msg: "ok", data: null });
            }

        } else {
            response.send({ code: "04", msg: "error", data: null });
        }
    })
})

//用户登录  验证码登录
app.get("/logins", (request, response) => {
    let { phonenum } = request.query
    userLogins(phonenum, res => {
        if (res.code === "01") {
            if (res.data.length >= 1) {
                response.send({ code: "01", msg: "ok", data: res.data[0] });
            } else {
                response.send({ code: "02", msg: "ok", data: null });
            }

        } else {
            response.send({ code: "04", msg: "error", data: null });
        }
    })
})

//学生信息认证
app.post("/approve", (request, response) => {
    let { realname, collage, uid, sex } = request.body
    userApprove(realname, collage, uid, sex, res => {
        if (res.code === "01") {
            response.send({ code: "01", msg: "ok", data: null })
        } else {
            response.send({ code: "04", msg: "err", data: null })
        }
    })
})

//用户信息的修改
app.post("/update", (request, response) => {
    let { nickname, phonenum, uid, email, age, head_url, signature } = request.body
        // 相当于加唯一标识符
    let head_filename = Date.now() + '.png';
    //存储图片的路径
    const imgPath = path.join(filePath, "/image/usersHead/") + head_filename;
    //去掉图片base64码前面部分data:image/png;base64
    const base64 = head_url.replace(/^data:image\/\w+;base64,/, "");
    //把base64码转成buffer对象，
    const dataBuffer = new Buffer(base64, 'base64');
    //文件的写入
    var head_urls = "/image/usersHead/" + head_filename
    fs.writeFile(imgPath, dataBuffer, function(err) {
        if (err) {} else {
            console.log('写入成功！');
        }
    });
    userUpdate(nickname, phonenum, uid, email, age, head_urls, signature, res => {
        if (res.code === "01") {
            response.send({ code: "01", msg: "ok", data: head_urls })
        } else {
            response.send({ code: "04", msg: "err", data: null })
        }
    })
})

// 图书发布
app.post("/bookSellRelease", (req, response) => {
    let bookinfo = req.body;
    let {
        cover: coverSrc,
        legend_1: legend_1Src,
        legend_2: legend_2Src,
        legend_3: legend_3Src,
    } = bookinfo;
    imgBuilderArr2([coverSrc, legend_1Src, legend_2Src, legend_3Src], "bookImgs", res => {
        bookinfo.cover = res[0];
        bookinfo.legend_1 = res[1];
        bookinfo.legend_2 = res[2];
        bookinfo.legend_3 = res[3];
        bookinfo.bid = uuid.v1();
        bookSellRelease(bookinfo, result => {
            if (result.code == "01") response.send({ code: "01", msg: "ok", data: bookinfo.bid });
            else response.send({ code: "04", msg: "error", data: null });
        })
    });
})


//获取大众喜欢书籍列表
app.get('/FavoriteBookList', (request, response) => {
    FavoriteBookList(res => {
        if (res.code === "01") response.send({ code: "01", msg: "ok", data: res.data })
        else response.send({ code: "04", msg: "err", data: null })
    })
})


// 获取附近在售列表 筛选未加入
app.post("/getBookOnSellList", (request, response) => {
    let { listType, filter } = request.body;
    switch (listType) {
        case "nearby":
            getBookOnSellNearBy(filter, (res) => {
                if (res.code == "01") response.send({ code: "01", msg: "ok", data: res.data });
                else response.send({ code: "04", msg: "error", data: null });
            });
            break;
        default:
            // 返回所有在售列表
    }
})

/*---获取书籍的详情信息(携带收藏信息)---*/

app.get("/bookinfo", (request, response) => {
    let {bid,uid} = request.query;
    getBookinfo(bid,uid, res => {
        if (res.code === "01") response.send({ code: "01", msg: "ok", data: res.data[0] })
        else  response.send({ code: "04", msg: "err", data: null })
    })
})

// 获取我的在售列表
app.get("/getMeOnSellBookList",(request, response)=>{
    let {uid} = request.query;
    getMeOnSellBookList(uid, res => {
        if (res.code === "01") response.send({ code: "01", msg: "ok", data: res.data })
        else  response.send({ code: "04", msg: "err", data: null })
    })
})



//添加或修改订单的地址
app.post("/Addaddress",(request,response)=>{
    console.log(request.body);
    let {aid,name,ipone,city,cityStr,detailed,isdefault,uid,flag} = request.body
    if(Number(flag)){
        updateAddaddress(aid,name,ipone,city,cityStr,detailed,isdefault,res=>{
            if(res.code==="01"){
                response.send({code:"01",msg:"ok",data:res.data})
            }else{
                response.send({code:"04",msg:"err",data:null})
            }
        })
    }else{
        getAddaddress(name,ipone,uid,city,cityStr,detailed,isdefault,uuid.v1(),res=>{
            if(res.code==="01"){
                response.send({code:"01",msg:"ok",data:res.data})
            }else{
                response.send({code:"04",msg:"err",data:null})
            }
        })
    }
})

//获取全部地址
app.get("/getAddress",(request,response)=>{
    console.log(request.query);
    let {uid} = request.query
    getAlladdress(uid,res=>{
        if(res.code==="01"){
            response.send({
                code:"01",
                msg:"ok",
                data:res.data
            })
        }else{
            response.send({
                code:"04",
                msg:"err",
                data:null
            })
        }
    })
});

//删除地址
app.post("/delAddress",(request,response)=>{
    let {aid} = request.body;
    delAddress(aid,res=>{
        if(res.code==="01"){
            response.send({
                code:"01",
                msg:"ok",
                data:res.data,
            })
        }else{
            response.send({
                code:"04",
                msg:"err",
                data:null,
            })
        }
    });
})
    
        
/*---获取我的收藏列表---*/
app.get("/getMefavorites",(request, response)=>{
    let {uid} = request.query;
    getMefavorites(uid, res => {
        if (res.code === "01") response.send({ code: "01", msg: "ok", data: res.data })
        else response.send({ code: "04", msg: "err", data: null })
    })
})

/*---图书收藏---*/ 
app.post("/setFavorite",(request, response)=>{
    let {bid, uid, isFavo} = request.body;
    setFavorite(uid,bid,isFavo,res=>{
        if (res.code === "01") response.send({ code: "01", msg: "ok", data: res.data })
        else response.send({ code: "04", msg: "err", data: null })
    })
})

//修改书籍价格
app.post("/AlterthepriceBook",(request,response)=>{
    let {bid,price} = request.body
    getAlterthepriceBook(bid,price,res=>{
        if (res.code === "01")  response.send({ code: "01", msg: "ok", data: null })
        else response.send({ code: "04", msg: "err", data: null })
    })
})

/*---图书发表评论---*/ 
app.post("/sendComment", (request,response)=>{
    let commentObj = request.body;
    commentObj.cid = uuid.v1();
    sendComment(commentObj,res=>{
        if (res.code === "01") response.send({ code: "01", msg: "ok", data: commentObj.cid })
        else response.send({ code: "04", msg: "err", data: null })
    })
});

/*---获取图书评论---*/ 
app.get("/getBookComments", (request,response)=>{
    let {bid} = request.query;
    getBookComments(bid,res=>{
        if (res.code === "01") response.send({ code: "01", msg: "ok", data:res.data })
        else response.send({ code: "04", msg: "err", data: null })
    })
})


//添加商品订单
app.post("/getOrders",(request,response)=>{
    let {uid,rece_address,paytype,paystatus, paysum,list} = request.body
    getorderLists(uid,rece_address,paytype,paystatus, paysum,list,res=>{
        if(res.code==="01"){
            response.send({
                code:"01",
                msg:"ok",
                data:res.data
            })
        }else{
            response.send({
                code:"04",
                msg:"err",
                data:null
            })
        }
    })
    
})

//获取未支付的订单
app.get("/getorder",(request,response)=>{
    console.log(request.query);
    let {oid} = request.query
    getOrder(oid,res=>{
        if(res.code==="01"){
            response.send({
                code:"01",
                msg:"ok",
                data:res.data
            })
        }else{
            response.send({
                code:"04",
                msg:"error",
                data:null
            })
        }
    })
})


//修改订单的状态
app.post("/updateOrder",(request,response)=>{
    console.log(request.body);
    
    response.send({
        code:"03",
        msg:"测试"
    })
})

//获取全部订单
app.get("/allOrderList",(request,response)=>{
    getAllorders(res=>{
        if(res.code==="01"){
            response.send({
                code:"01",
                msg:"ok",
                data:res.data
            })
        }else{
            response.send({
                code:"04",
                msg:"err",
                data:null
            })
        }
    })
})

//获取支付或未支付订单
app.get("/orders",(request,response)=>{
    console.log(request.query);
    let {paystatus} = request.query
    getorders(paystatus,res=>{
        if(res.code==="01"){
            response.send({
                code:"01",
                msg:"ok",
                data:res.data
            })
        }else{
            response.send({
                code:"04",
                msg:"err",
                data:null
            })
        }
    })
})


//获取订单对应的商品
app.get("/getgoods",(request,response)=>{
    console.log(request.query);
    let {oid} = request.query 
    getGoods(oid,res=>{
        if(res.code==="01"){
            response.send({
                code:"01",
                msg:"ok",
                data:res.data
            })
        }else{
            response.send({
                code:"04",
                msg:"err",
                data:null
            })
        }
    })
})

//获取热搜的书籍
app.get('/hotLists',(request,response)=>{
    getHotLists(res=>{
        if(res.code==="01"){
            response.send({
                code:"01",
                msg:"ok",
                data:res.data
            })
        }else{
            response.send({
                code:"04",
                msg:"err",
                data:null
            })
        }
    })
})

/*---获取消息队列---*/
app.get("/getMeMessageAll", (request,response)=>{
    let {uid} = request.query;
    getMeMessageAll(uid,res=>{
        if (res.code === "01") response.send({ code: "01", msg: "ok", data:res.data })
        else response.send({ code: "04", msg: "err", data: null })
    })
})


//
app.post("/pullChatRecords",(request,response)=>{
    let msgObj = request.body;
    pullChatRecords(msgObj,res=>{
        if (res.code === "01") response.send({ code: "01", msg: "ok", data:res.data })
        else response.send({ code: "04", msg: "err", data: null })
    })
})

/*---按类别搜索图书---*/
app.get("/searchBookByType",(request,response)=>{
    let {typeFilter} = request.query;
    searchBookByType(typeFilter,res=>{
        if (res.code === "01") response.send({ code: "01", msg: "ok", data:res.data })
        else response.send({ code: "04", msg: "err", data: null })
    })
})


/*--- 图书关键词搜索 ---*/
app.get("/searchBooksByKey",(request,response)=>{
    let {keyWord} = request.query;
    searchBooksByKey(keyWord,res=>{
        if (res.code === "01") response.send({ code: "01", msg: "ok", data:res.data })
        else response.send({ code: "04", msg: "err", data: null })
    })
})





/*---get default---所有接口写在此接口之上---*/
app.get("*", (request, response) => {
    // response.redirect("./404.html");
    console.log("get-->*")
    response.send({ code: "404", msg:"get/*"});
});
/*---post default---所有接口写在此接口之上---*/
app.post("*", (request, response) => {
    // response.redirect("./404.html");
    console.log("post-->*")
    response.send({ code: "404",msg:"post/*" });
});


